'use strict';
let excel = require('./admin.channel.excel');
const mongoose = require('mongoose');

let censusList = async function(options={addDate:'2019-03-05'}){
    let censusModel=mongoose.models['Census'];
    let channelModel=mongoose.models['Channel'];
    let channelCensusModel=mongoose.models['ChannelCensus'];

    let list = [];
    let channels = await channelModel.find({});
    for(let channel of channels){
        let channelCensus = await channelCensusModel.findOne({channelId: channel._id.toString(), addDate:options.addDate});
        if(!channelCensus){
            continue;
        }
        channelCensus = channelCensus._doc;

        let startTime = new Date(options.addDate).getTime();
        let obj = {group:'渠道日统计', type: channelCensus.channelId, timeTick: {$gt: startTime + 3000, $lt: (startTime + 86400000 + 3000)}};
        let censusData = await censusModel.findOne(obj);

        channelCensus.channelUserCount = censusData ? censusData.count : 0;
        channelCensus.timeTick = censusData ? censusData.timeTick : 0;
        channelCensus.channelUserCountAfter = censusData && censusData.setCount ? censusData.setCount : '-';
        channelCensus.registerUserPer = Math.round(channelCensus.registerUserCount / channelCensus.navigateUserCount * 100);    // 注册用户占比
        channelCensus.priceUser = channel.allCount || 0;                       // 计价用户
        channelCensus.settlementPer = channelCensus.percent || channel.percent;                    // 结算百分比
        channelCensus.channelPer = Math.round(channelCensus.registerUserPer * channelCensus.settlementPer / 100);     // 渠道百分比
        channelCensus.settlementUser = Math.round(channelCensus.priceUser * (channelCensus.settlementPer / 100));       // 结算用户
        channelCensus.channelId = channel._id.toString();
        channelCensus.nowPercent = channel.percent;
        list.push(channelCensus);
    }
    list.sort( (a, b) => {return b.registerUserCount != a.registerUserCount ? (b.registerUserCount - a.registerUserCount) : (b.navigateUserCount - a.navigateUserCount);
    });
    return list;
};


module.exports={
    list:async function(options){
        let ChannelModel=mongoose.models['Channel'];
        let queryData = {};
        if(!!options.channelLoginId && options.channelLoginId.length>0){
            queryData.loginId = eval('/'+options.channelLoginId+'/i');
        }
        if(!!options.name && options.name.length>0){
            queryData.name = eval('/'+options.name+'/i');
        }
        let channels=await ChannelModel.find(queryData);
        channels.sort((a,b)=>{return b.sort-a.sort;});
        return channels;
    },
    add:async function(options){
        let ChannelModel=mongoose.models['Channel'];
        options.loginId=options.channelLoginId;
        await ChannelModel.create(options);
    },
    edit:async function(options){
        let ChannelModel=mongoose.models['Channel'];
        let channel=await ChannelModel.findOne({_id:options._id});
        if(!channel){
            throw new Error('这个渠道不存在');
        }
        delete options._id;
        options.loginId=options.channelLoginId;
        await ChannelModel.updateOne({_id:channel._id},{$set:options}).exec();
    },
    delete:async function(options){
        let ChannelModel=mongoose.models['Channel'];
        let channel=await ChannelModel.findOne({_id:options._id});
        if(!channel){
            throw new Error('这个渠道不存在');
        }
        await ChannelModel.deleteOne({_id:options._id});
    },
    remainList:async function(options={channelId:'abc'}){ //渠道日统计
        let CensusModel=mongoose.models['Census'];
        let obj = {
            type: options.channelId,
            group: '渠道日统计',
            timeTick: {
                $gte: new Date(new Date().toLocaleDateString()).getTime() - 30 * 24 * 60 * 60 * 1000,
                $lte: new Date(new Date().toLocaleDateString()).getTime()
            }
        };
        if(!!options.time1){
            obj.timeTick.$gte = parseInt(options.time1);
        }
        if(!!options.time2){
            obj.timeTick.$lte = parseInt(options.time2);
        }
        // console.log('remainList obj =', obj);
        let censuses=await CensusModel.find(obj).sort({timeTick:-1});
        return censuses;
    },
    editSetCount: async function(options){
        let CensusModel=mongoose.models['Census'];
        let data = await CensusModel.updateOne({type: options.channelId, group: '渠道日统计', timeTick: options.timeTick}, {setCount: options.setCount});
        console.log('data ==', data, options);
    },
    //渠道统计总数据列表
    censusList: censusList,
    chanelDayTotalExcel1: async function(options){
        let list = await censusList(options);
        let data = await excel.channelDayTotalExcel1(list);
        return data;
    },
    chanelDayTotalExcel2: async function(options){
        let list = await censusList(options);
        let data = await excel.channelDayTotalExcel2(list);
        return data;
    },
    editPercent: async function(options){
        let ChannelModel = mongoose.models['Channel'];
        let channel = await ChannelModel.findOne({_id:options.channelId});
        if(!channel){
            throw new Error('这个渠道不存在');
        }
        channel.percent = options.percent;
        await channel.save();
    },
};
